<?php
namespace Home\Controller;
use Common\Model\ActivityModel;
use Home\Model\CartsModel;
use Think\Controller;
use Home\Event\WeixinEvent;
use Home\Event\JssdkEvent;

//set_time_limit(100);
class OrdersController extends BaseController {


    public $member_id;
    public function __construct(){
        parent::__construct();
        $this->member_id = $this->member_data['member_id'];
        if(!$this->member_id){
            $this->redirect('Login/index');
        }
    }


    use ActivityModel;
    /**
     * 订单结算页面
     */
    public function checkOut(){

        $result = $this->checkDet();
        //print_r($result);exit;
        foreach ($result as $k=>&$value){
            if($value['lp_fee']==0){
                continue;
            }

            //先订单促销
             $result[$k] = $this->orderPro($value);
            //print_r($result[$k]['order_pro']);exit;
            //订单促销后的价格
             $orderProPrice = $result[$k]['lp_fee']- $result[$k]['disOrderMoney'] + $result[$k]['ship_fee'];

            //促销过后 订单价格，来评判，订单满 X 元 ，可以用
            $cou =  $this->isCanCoupon(session('userInfo')['member_id'],$value['local_id'],$orderProPrice,$value['products']);

            if(!empty($cou)){
                $value['coupon'] = $cou;
            }
            foreach ($value['products'] as $kk=>$vv){
                if($vv['type']==1 && $vv['ischeck']==1 && ($vv['active']==1||$vv['active_ident']==1)){
                    $value['tc_num'] += $vv['cart_num'];
                }
            }
        }
        //订单促销显示
      // print_r($result);


        /***---------送货时间---------******/

        $total['ship_fee'] = 0;
        $total['total_fee'] = 0;
        $total['save'] = 0;
        $inum = 0;
        foreach ($result as $k=>$local){
            //总运费
            /*if($local['ship_fee_status']==1){
                $local['ship_fee'] = '免运费';
            }*/
            $total['ship_fee']  = $total['ship_fee'] + $local['ship_fee'] - $local['ship_fee_l'];
            $total['total_fee'] += $local['local_total'];
            $total['discMoney'] += $local['discMoney'];
            $total['coupon'] += count($local['gift_coupon']);
            //单个店铺商品 共优惠多少钱
            if($local['ship_fee_status']==1){
                $sheng_count = $local['lp_fee'] - $local['local_total'];
            }else{
                $sheng_count = $local['lp_fee'] - ($local['local_total']-$local['ship_fee']);
            }
            //免运费提示
            if($local['ship_fee_status']==1 || $local['ship_fee']==0){
                $result[$k]['free'] = 1;
            }else{
                $result[$k]['free'] = 0;
            }
            if($result[$k]['checked_num']!=0){
                $inum++;
            }

            $result[$k]['inum'] = $inum;

            if($sheng_count > 0){
                $total['save'] += $sheng_count;
            }


        }


        $this->assign('total',$total);




        $this->assign('checkout',$result);
        $this->display();
    }
    //订单促销
    public function orderPro($value){

        //订单满足哪些订单促销条件
        $order_pro = $this->isOrder($value['local_id'],$value['lp_fee'],$value['products']);

        //满足条件进行排序选择 用哪一个 订单促销
        $resultOrder_pro = array();
        if(!empty($order_pro)){

            foreach ($order_pro as $op=>$item){


                $arr = [];
                $arr1 = [];
                foreach ($item as $i=>$ival){
                    if($ival['rule']==1){
                        //判断是否是排他
                        $arr[] = $ival['paita'];
                        $arr1[] = $ival['sort'];
                    }

                }
                array_multisort($arr, SORT_DESC,$arr1,SORT_ASC ,$item);


                //处理选择用哪一个订单促销
                foreach ($item as $it =>$itval){

                    if($itval['paita']=='1'){
                        $resultOrder_pro[] = $itval;
                        break;
                    }elseif($itval['paita']=='0'){
                        $resultOrder_pro[] = $itval;
                    }
                }



            }
        }



        //处理订单促销
        $discMoney = 0;

        foreach ($resultOrder_pro as $key=>$vl){
            if(isset($vl['gift']['coupon']) && empty($vl['gift']['coupon'])){
                unset($resultOrder_pro[$key]);
                continue;
            }


            if($vl['type_result']=='1'){
                $value['local_total'] = $value['local_total'] - $value['ship_fee'];
                $value['ship_fee_l'] = $value['ship_fee'];
                $discMoney += $value['ship_fee'];
                $value['order_pro'][$key] = $vl;
                $value['order_pro'][$key]['disc_ship_fee'] = $value['ship_fee'];

                $value['ship_fee_status'] = 1;

            }elseif ($vl['type_result']=='2'){
                //订单商品总价 < 订单促销模式

                if($value['local_total'] <= $vl['gift']['discount_price']){
                    continue;
                }
                $value['local_total'] = $value['local_total'] - $vl['gift']['discount_price'];
                $discMoney += $vl['gift']['discount_price'];
                $value['order_pro'][$key] = $vl;
            }elseif ($vl['type_result']=='3'){
                if(isset($value['gift_coupon'])){
                    $value['gift_coupon'] = array_merge($value['gift_coupon'],$vl['gift']['coupon']);
                }else{
                    $value['gift_coupon'] = $vl['gift']['coupon'];
                }
                $value['order_pro'][$key] = $vl;

            }



        }

        $value['disOrderMoney'] = $discMoney;

        return $value;


    }


    //订单满足哪些订单促销条件

    public function isOrder($local_id,$total,$products){
        $now_time = date("Y-m-d H:i:s", time());
        $orderRule = M('b2c_store_order_promotion')->where(['display'=>'1','end_time'=>['gt',$now_time],'start_time'=>['lt',$now_time],'local_id'=>$local_id])->select();
        $orderRuleOk = array();


        foreach ($orderRule as $k=>$value){

            if ($value['type_question']=='1') {
                //促销条件1：订单金额满 X 元时，对指定商品促销
                if($total>=$value['question_man_price']){
                    //满足多少促销
                        $pArr= [];
                        //包含
                        $postt =  strpos($value['question_goods_id_array'],'#');
                        if($postt !== false){
                            $pArr = explode('#',$value['question_goods_id_array']);
                        }else{
                            $pArr[] = $value['question_goods_id_array'];
                        }
                        /*print_r($pArr);
                        print_r($products);*/
                        foreach ($products as $kk=>$val){
                            if(($val['active']==1 || $val['active_ident']==1) && $val['ischeck']==1 && $val['store_status']=='true'){
                                //激活选中商品
                                if($val['type']==0){
                                    //普通商品
                                    if ((in_array($val['store_pid'], $pArr) && $value['question_include'] == '1') || (in_array($val['store_pid'], $pArr) === false && $value['question_include'] == '0')) {

                                        $Rule['rule'] = 1;
                                        $Rule['id'] = $value['id'];
                                        $Rule['local_id'] = $local_id;
                                        $Rule['paita'] = $value['paita'];
                                        $Rule['sort'] = $value['sort'];
                                        $Rule['description'] = $value['description'];
                                        $Rule['type_question'] = $value['type_question'];
                                        $Rule['name'] = $value['name'];
                                        $Rule['type_result'] = $value['type_result'];
                                        //满足条件 赠送
                                        $Rule['gift'] = $this->giftType($value);
                                        $orderRuleOk['type_result'.$value['type_result']][] = $Rule;

                                        unset($Rule);
                                        break;
                                     }

                                }elseif ($val['type']==1){
                                    //组合商品
                                    foreach ($val['group_products'] as $v) {
                                        if ((in_array($v['store_pid'], $pArr) && $value['question_include'] == '1') ||(in_array($val['store_pid'], $pArr) === false && $value['question_include'] == '0')) {
                                            $Rule['rule'] = 1;
                                            $Rule['id'] = $value['id'];
                                            $Rule['local_id'] = $local_id;
                                            $Rule['paita'] = $value['paita'];
                                            $Rule['sort'] = $value['sort'];
                                            $Rule['description'] = $value['description'];
                                            $Rule['type_question'] = $value['type_question'];
                                            $Rule['name'] = $value['name'];
                                            $Rule['type_result'] = $value['type_result'];
                                            //满足条件 赠送
                                            $Rule['gift'] = $this->giftType($value);
                                            $orderRuleOk['type_result'.$value['type_result']][] = $Rule;

                                            unset($Rule);
                                            break 2;

                                        }
                                    }

                                }
                            }
                        }


                }


            }elseif ($value['type_question']=='2'){
                //促销条件2：订单金额满 X 元时，对所有订单促销
                if($total>=$value['question_man_price_two']){
                    $Rule['rule'] = 1;
                    $Rule['id'] = $value['id'];
                    $Rule['local_id'] = $local_id;
                    $Rule['paita'] = $value['paita'];
                    $Rule['sort'] = $value['sort'];
                    $Rule['description'] = $value['description'];
                    $Rule['type_question'] = $value['type_question'];
                    $Rule['name'] = $value['name'];
                    $Rule['type_result'] = $value['type_result'];
                    $Rule['gift'] = $this->giftType($value);
                    /*if(empty($orderRuleOk[$k]['gift']['coupon'])&&$orderRuleOk[$k]['gift']['type']==3){
                        unset($orderRuleOk[$k]);
                        continue;
                    }*/

                    $orderRuleOk['type_result'.$value['type_result']][] = $Rule;

                    unset($Rule);

                }

            }elseif ($value['type_question']=='3'){
                //促销条件3：所有订单
                $Rule['rule'] = 1;
                $Rule['id'] = $value['id'];
                $Rule['local_id'] = $local_id;
                $Rule['paita'] = $value['paita'];
                $Rule['sort'] = $value['sort'];
                $Rule['description'] = $value['description'];
                $Rule['type_question'] = $value['type_question'];
                $Rule['name'] = $value['name'];
                $Rule['type_result'] = $value['type_result'];
                $Rule['gift'] = $this->giftType($value);

                $orderRuleOk['type_result'.$value['type_result']][] = $Rule;

                unset($Rule);



            }

        }

        return $orderRuleOk;
    }


    //订单促销，满足条件后赠送方式
    /**
     * @param $val  规则
     */
    public function giftType($val){
        static $a;
        //print_r($val);
        $gift = array();
        if($val['type_result']=='1'){
            $gift['type'] = 1;
            $gift['type_name'] = '订单免运费';
        }elseif ($val['type_result']=='2'){

            $gift['type'] = 2;
            $gift['discount_price'] = $val['result_price'];
            $gift['type_name'] = '订单减去X价格';
        }elseif ($val['type_result']=='3'){
            //送优惠卷
            $gift['type'] = 3;
            $gift['type_name'] = '送优惠卷';

            //$gift['coupon']
            //分配 赠送优惠卷
            $disPos =  strpos($val['result_discount_coupon'],'#');
            if($disPos !== false){
                $pArr = explode('#',$val['result_discount_coupon']);
            }else{
                $pArr[] = $val['result_discount_coupon'];
            }
            if(empty($a)){
                $where = "1=1 ";
            }else{
                $where = "1=1 and cc.id not in (".join(',', $a).")";
            }


            foreach ($pArr as $k=>$item){
                //选择一张优惠卷
                $cou =  M('b2c_discount_coupon_code cc')
                    ->join("left join ".C('DB_PREFIX')."b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id ")
                    ->where(['cc.local_id'=>$val['local_id'],'dc.id'=>$item,'cc.member_id'=>0,'cc.status'=>'0', $where])
                    ->order('dc.sort asc')
                    ->field('cc.id')
                    ->find();
                //echo M()->getlastSql();
                if(!empty($cou['id'])){
                    $a[] = $cou['id'];
                }
                $gift['coupon'][$k] = $cou['id'];

                //如果赠送的优惠价已经送完
                if(empty($cou['id'])){
                    unset($gift['coupon'][$k]);
                }
            }

        }
        return $gift;

    }

    //能使用的优惠卷
    public function isCanCoupon($member_id,$local_id,$local_total,$products){
       // echo $member_id."|".$local_id."|".$local_total."|".$products;
        //优惠卷  未使用，未过期
            $cou =  M('b2c_discount_coupon_code cc')
                ->join("left join ".C('DB_PREFIX')."b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id ")
                ->where(['cc.member_id'=>$member_id,'cc.status'=>'0','cc.local_id'=>$local_id])
                ->order('dc.sort asc')
                ->field('dc.*,cc.discount_coupon_id,cc.code,cc.member_id,cc.status')
                ->select();
            //echo M()->getlastSql();

            foreach ($cou as $j=>$val){

                //根据店铺购买总价格，满足使用的
                if(time()< strtotime($val['end_time']) && time()> strtotime($val['start_time'])){

                    $canCoupon[$j] = $val;
                    $canCoupon[$j]['Is_use'] = 0;
                    $canCoupon[$j]['discmoney'] = 0;
                    $canCoupon[$j]['to_money'] = number_format("0",2,".",".");
                    if($val['type']=='1'&& ($local_total-$val['money_price'])>0){
                        //3-3 冉  现金卷 针对某些商品 不能使用
                        $pArr = [];
                        $postt =  strpos($val['goods_id_array'],'#');
                        if($postt !== false){
                            $pArr = explode('#',$val['goods_id_array']);
                        }else{
                            $pArr[] = $val['goods_id_array'];
                        }

                        $is_found_goods = false;
                        foreach ($products as $kk=>$v){
                            if(($v['active']==1 ||$v['active_ident']==1) && $v['ischeck']==1 && $v['store_status']=='true'){
                                //激活选中商品
                                if($v['type']==0){
                                    //普通商品
                                    if ((in_array($v['store_pid'], $pArr) && $val['is_include'] == '0') ) {
                                        $is_found_goods = true;
                                        break;
                                    }

                                }elseif ($v['type']==1){
                                    //组合商品
                                    foreach ($v['group_products'] as $vv) {
                                        if ((in_array($vv['store_pid'], $pArr) && $val['is_include'] == '0')) {
                                            $is_found_goods = true;
                                            break 2;
                                        }
                                    }

                                }
                            }
                        }
                        if($is_found_goods){
                            $canCoupon[$j]['Is_use'] = 0;
                        }else{
                            $canCoupon[$j]['Is_use'] = 1;
                            $canCoupon[$j]['discmoney'] = $val['money_price'];
                        }

                    /**************************************************************************/


                    }elseif($val['type']=='2' && $local_total>=$val['man_price'] && ($local_total-$val['youhui_price'])>=1){
                        //3-3 冉  订单优惠卷 针对某些商品 不能使用
                        $pArr = [];
                        $postt =  strpos($val['goods_id_array'],'#');
                        if($postt !== false){
                            $pArr = explode('#',$val['goods_id_array']);
                        }else{
                            $pArr[] = $val['goods_id_array'];
                        }
                        $is_found_goods = false;
                        foreach ($products as $kk=>$v){
                            if(($v['active']==1||$v['active_ident']==1) && $v['ischeck']==1 && $v['store_status']=='true'){
                                //激活选中商品
                                if($v['type']==0){
                                    //普通商品
                                    if ((in_array($v['store_pid'], $pArr) && $val['is_include'] == '0') ) {
                                        $is_found_goods = true;
                                        break;
                                    }

                                }elseif ($v['type']==1){
                                    //组合商品
                                    foreach ($v['group_products'] as $vv) {
                                        if ((in_array($vv['store_pid'], $pArr) && $val['is_include'] == '0')) {
                                            $is_found_goods = true;
                                            break 2;
                                        }
                                    }

                                }
                            }
                        }
                        if($is_found_goods){
                            $canCoupon[$j]['Is_use'] = 0;
                        }else{
                            $canCoupon[$j]['Is_use'] = 1;
                            $canCoupon[$j]['discmoney'] = $val['youhui_price'];
                            $canCoupon[$j]['to_money'] = $val['man_price'];
                        }

                        /**************************************************************************/


                    }elseif($val['type']=='3'&& ($local_total-$val['goods_price'])>=1){
                        $pArr = [];
                        $postt =  strpos($val['goods_id_array'],'#');
                        if($postt !== false){
                            $pArr = explode('#',$val['goods_id_array']);
                        }else{
                            $pArr[] = $val['goods_id_array'];
                        }
                        //print_r($pArr);
                        foreach ($products as $p=>$item){
                            if(($item['active']==1||$item['active_ident']==1) && $item['ischeck']==1 && $item['store_status']=='true'){
                                    if($item['type']==0){
                                        foreach ($pArr as $sp){
                                            if($sp == $item['store_pid']){
                                                $canCoupon[$j]['Is_use'] = 1;
                                                $canCoupon[$j]['discmoney'] = $val['goods_price'];
                                            }
                                        }
                                    }elseif($item['type']==1){
                                        foreach ($pArr as $sp){
                                            foreach ($item['group_products'] as $gp){
                                                if($sp == $gp['store_pid']){
                                                    $canCoupon[$j]['Is_use'] = 1;
                                                    $canCoupon[$j]['discmoney'] = $val['goods_price'];
                                                }
                                            }
                                        }
                                    }
                            }

                        }
                    }
                    if($val['paita']=='1'){
                        $canCoupon[$j]['Ispaita'] = 1;
                    }else{
                        $canCoupon[$j]['Ispaita'] = 0;
                    }

                   if($canCoupon[$j]['Is_use'] == 0){
                       unset($canCoupon[$j]);
                   }

                }

            }

        return $canCoupon;

    }


    //订单结算详细
    public function checkDet(){
        $model = new CartsModel();
        $result = $model->getCartData($this->member_id);


        $this->assign('addr',$result['address']);
        $addr = $result['address']['area'];
        if(!empty($result['out_time'])){
            unset($result['out_time']['lp_fee']);
            unset($result['out_time']['shop_checkd']);
            unset($result['out_time']['distance']);
            unset($result['out_time']['shipping']);
            unset($result['out_time']['ship_fee']);
            unset($result['out_time']['total_weight']);
            unset($result['out_time']['store_dot_name']);
        }
        unset($result['out_time']);
        unset($result['clearAll']);
        unset($result['address']);
        unset($result['total_fee']);
        unset($result['goods_total_fee']);
        unset($result['all_check']);

        unset($result['store_ok']);
        unset($result['tips']);

        unset($result['no_goods']);
        unset($result['no_address']);
        unset($result['is_no_check']);

        foreach ($result as $k=>$local){
            //奖金渲染
            $user_bonus = M('distribution_member dm')->where(['local_id'=>$local['local_id'],'member_id'=>$this->member_id])->find();
            $result[$k]['bonus_money'] = $user_bonus['current_bonus'];
            //门店的给上级的比例奖金
            $user_bonus_ok = M('distribution_member dm')
                ->join('left join sdb_webpos_local_store ls on ls.local_id = dm.local_id')
                ->join('left join sdb_store_distribution_set ds on ds.local_id = dm.local_id')
                ->where(['dm.local_id'=>$local['local_id'],'dm.member_id'=>$this->member_id,'ls.is_open_distribution'=>'1','ls.local_status'=>'1',
                    'ds.set_name'=>'son_shopping'])->find()['set_value'];
            if(!empty($user_bonus_ok)){
                //店铺开启，并开启分销
                $result[$k]['bonus_proportion'] = $user_bonus_ok*0.01;
            }else{
                $result[$k]['bonus_proportion'] = 0;
            }



            if($local['is_self']==1){
                //全国送 数据重组
                $res = array();
                foreach ($local['products'] as $kk =>$it){
                    if($it['ischeck']==1 && $it['active_ident'] == 1){
                        $res[$it['supplier_id']][] = $it;
                    }
                }
               unset($local['products']);

                $new_local = array();
                foreach ($res as $t=>$tval){
                    $new_local = $local;
                    //计算进口税
                    $import_money = 0;
                    $import_weight = 0;
                    $lp_fee = 0;
                    $lid = 0;
                    $checked_num = 0;
                     foreach ($tval as $vvv){
                         $import_money += $vvv['import_duty'];
                         /*如果有组合商品*/
                         if(isset($vvv['group_products'])){
                            foreach ($vvv['group_products'] as $grkey => $g_p){
                                $import_money += $g_p['import_duty']*$g_p['num'];
                            }
                         }



                         $import_weight += $vvv['weight'] * $vvv['cart_num'];
                         $lp_fee += $vvv['final_price'] * $vvv['cart_num'];
                         $checked_num ++;
                         $lid = $vvv['local_id'];
                     }
                    $new_local['import_duty'] = $import_money;
                    $new_local['total_weight'] = $import_weight;
                    $new_local['supplier_id'] = $t;
                    $new_local['lp_fee'] = $lp_fee;
                    //计算运费  重量
                    $qgs_res =  $this->qgs_yf($t,$import_weight,$addr,$lid);

                    $new_local['ship_fee'] =  $qgs_res['cost_freight'];
                    $new_local['area_start'] =  $qgs_res['area_start'];
                    //店铺总费用
                    $new_local['local_total'] = $new_local['lp_fee'] + $new_local['import_duty'] + $new_local['ship_fee'];
                    $new_local['checked_num'] = $checked_num;

                    $new_local['products'] = $tval;
                    $result[] =$new_local;

                }

                unset($result[$k]);


            }

        }

        return $result;
    }

    /*
     * 全国送计算运费
     * */
    public function qgs_yf($supplier_id=0,$total_weight=0,$addr='',$local_id){


        $popps = strpos($addr, '/');
        $yf_addr = substr($addr, $popps + 1);
        $yf_addr = str_replace("/", "", $yf_addr);

        //如果$supplier_id = 0 用店铺运送模板计算运费
        if($supplier_id == 0){
            $dlytmp = M('b2c_dlyyctmp')->where(['local_id' => $local_id])->field('firstunit,continueunit,firstprice,continueprice')->find();
            $area_addr = M('qgs_supplier')->where(['supplier_id' => $supplier_id])->find()['province'];
        }else{
            //有 supplier_id
            $dlytmp = M('qgs_supplier qs')
                ->join("left join ".C('DB_PREFIX')."b2c_dlytmp dt on dt.tmp_id = qs.expres_template and dt.local_id = qs.local_id ")
                ->where([ 'qs.supplier_id' => $supplier_id, 'dt.area_group_id' => array('like', "%" . $yf_addr . "%")])->field('dt.firstunit,dt.continueunit,dt.firstprice,dt.continueprice,dt.qyname,qs.province')->find();

            if (empty($dlytmp)) {
                $dlytmp = M('qgs_supplier qs')
                    ->join("left join ".C('DB_PREFIX')."b2c_dlytmp dt on dt.tmp_id = qs.expres_template and dt.local_id = qs.local_id ")
                    ->where([ 'qs.supplier_id' => $supplier_id,'dt.is_def' => 1])->field('dt.firstunit,dt.continueunit,dt.firstprice,dt.continueprice,dt.qyname,qs.province')->find();
            }

        }


        if ($total_weight <= ($dlytmp['firstunit'] * 1000)) {
            $cost_freight = $dlytmp['firstprice'];
        } else {
            $price = ceil(($total_weight - ($dlytmp['firstunit'] * 1000)) / ($dlytmp['continueunit'] * 1000)) * $dlytmp['continueprice'];
            $cost_freight = $dlytmp['firstprice'] + $price;
        }

        $cost_freight_s['cost_freight'] = $cost_freight;
        if($supplier_id == 0){
            $cost_freight_s['area_start'] = $area_addr;
        }else{
            $cost_freight_s['area_start'] = $dlytmp['province'];
        }

        return $cost_freight_s;
    }

    /**
     * 订单创建  事务回滚【要用】
     */
    public function cartOrder()
    {

        $data = $_POST['data'];

        //订单后台验证
        //print_r($data['order']);


        /*
         * 数据准确性判断
         * */
        $carts=(new CartsModel('carts'))->getCartData($this->member_id);


        //判断商品库存是否足够
        if($carts['store_ok']==0){
            return $this->ajaxReturn(array('msg'=>$carts['tips'],'status'=>0));
        }
        if($carts['no_goods']==1){
            return $this->ajaxReturn(array('msg'=>'购物车没商品','status'=>0));
        }
        if($carts['no_address']==1){
            return $this->ajaxReturn(array('msg'=>'请添加收货地址','status'=>0));
        }
        if($carts['is_no_check']==0){
            return $this->ajaxReturn(array('msg'=>'请再购物车中勾选要购买的商品','status'=>0));
        }

        if(!empty($carts['out_time'])){
            unset($carts['out_time']);
        }
        $userAddr = $carts['address'];
        unset($carts['clearAll']);
        unset($carts['address']);


        unset($carts['total_fee']);
        unset($carts['all_check']);
        unset($carts['store_ok']);
        unset($carts['tips']);
        unset($carts['no_goods']);
        unset($carts['no_address']);
        unset($carts['is_no_check']);

        $carts=$this->checkDet();
        foreach ($carts as $k=>$v){
            $carts[$k] = $this->orderPro($v);  //订单促销 后的订单信息，包含订单促销后的，店铺应付付的价格
        }


        //判断支付方式
        $pay_id = 0;

        $coupon_array = array();
        foreach ($data['order'] as $tt=>$item){

            //判断支付参数是否异常
            $is_find = M('b2c_payment')->where(['name'=>$item['pay_method'],'id'=>$item['pay_method_id']])->find();
            $pay_id = $item['pay_method_id'];
            if(empty($is_find)){
                $this->ajaxReturn(array('msg'=>'数据异常','status'=>0));
            }
            //判断 优惠卷是否异常
           foreach ($item['coupons'] as $k=>$val){
             $find_coupon =  M('b2c_discount_coupon_code cc')
                 ->join("left join ".C('DB_PREFIX')."b2c_discount_coupon dc on cc.discount_coupon_id = dc.id and cc.local_id = dc.local_id ")
            ->where(['cc.code'=>$val[0],'cc.discount_coupon_id'=>$val[1],'cc.local_id'=>$val[2],'cc.member_id'=>session('userInfo')['member_id'],'cc.status'=>['neq','1'] ])
                 ->field('dc.*,cc.discount_coupon_id,cc.code,cc.member_id,cc.status,cc.id as coupon_id')
                 ->find();

               //echo M()->getlastSql();
             if(empty($find_coupon)){
                 $this->ajaxReturn(array('msg'=>'数据异常','status'=>0));
             }else{
                 //判断是否是排他，如果是排他只取满足条件的排他那条优惠卷
                 if($find_coupon['paita']=='1'){
                     $coupon_array[$item['local_id']][$k] = $find_coupon;
                     $coupon_array[$tt]['paita'] = 1;
                 }else{
                     $coupon_array[$item['local_id']][$k] = $find_coupon;
                 }
             }
           }

        }


        //1.比较总价
        //if($carts['total_fee']==$data[''])
        //2.比较单个店铺的商品
        for($i=0;$carts[$i];$i++){
            $lastcoupon_pd = array();
            //print_r($coupon_array);
            //正确的优惠卷数组
            foreach ($coupon_array as $vv => $ca){
                if($vv == $carts[$i]['local_id']){
                    $lastcoupon_pd =  $this->choice($ca,$carts[$i]['local_total']);
                }
            }

            if(!empty($lastcoupon_pd)){
                $carts[$i]['payMoney'] = $lastcoupon_pd['money'];
            }else{
                $carts[$i]['payMoney'] = $carts[$i]['local_total'];
            }

            for($j=0;$data['order'][$j];$j++){
                //如果店铺相同,比较店铺总费用和运费
                if($carts[$i]['local_id']==$data['order'][$j]['local_id']){

                    $carts[$i]['local_total'] =  number_format($carts[$i]['local_total'], 2, '.', '');
                    $carts[$i]['ship_fee'] =  number_format($carts[$i]['ship_fee'], 2, '.', '');
                    $carts[$i]['payMoney'] =  number_format($carts[$i]['payMoney'], 2, '.', '');
                    //检查用户使用的金额是否是大于了 他本身的金额
                    if($data['order'][$j]['bonus'] > 0){
                           $max_bonus = M('distribution_member')->where(['local_id'=>$carts[$i]['local_id'],'member_id'=>$this->member_id])->find()['current_bonus'];
                           if($max_bonus < $data['order'][$j]['bonus']){
                               $this->ajaxReturn(array('msg'=>'使用奖金异常！','status'=>0));
                           }
                    }
                    //使用奖金 5-19
                    $carts[$i]['payMoney'] =  $carts[$i]['payMoney'] - $data['order'][$j]['bonus'];

                    //echo $carts[$i]['payMoney'].'|'. $data['order'][$j]['local_total'];


                    $carts[$i]['payMoney'] =  number_format($carts[$i]['payMoney'], 2, '.', '');
                    $data['order'][$j]['local_total'] = number_format($data['order'][$j]['local_total'], 2, '.', '');
                    if($carts[$i]['payMoney']!=$data['order'][$j]['local_total']){
                        //echo $carts[$i]['payMoney'].'|'.$data['order'][$j]['local_total'];
                        $this->ajaxReturn(array('msg'=>'总价不符合','status'=>0));
                    }
                    if($carts[$i]['ship_fee']!=$data['order'][$j]['cost_freight']){
                        $this->ajaxReturn(array('msg'=>'运费不符合','status'=>0));
                    }
                }
            }
            unset($carts[$i]['payMoney']);
        }

        //判断通过

        $orderGroup = array();



        //判断优惠卷 是否是 正确能提交的优惠卷
        foreach ($carts as $k=>$value){
            $cou =  $this->isCanCoupon(session('userInfo')['member_id'],$value['local_id'],$value['local_total'],$value['products']);
            //print_r($cou);
            if(!empty($cou)){
               //提交过来的数据找到对应的门店能用的优惠卷匹配 是否存在此优惠卷
                foreach ($data['order'] as $k=>$local){
                    if($local['local_id']==$value['local_id']){
                        foreach ($local['coupons']  as $lk =>$vv ){
                            $isin = $this->deep_in_array($vv[0], $cou);
                            if($isin === false){
                                $this->ajaxReturn(array('msg'=>'数据异常','status'=>0));
                                break;
                            }
                        }

                    }

                }
            }
        }

        //事物开启
        $Mod = M();
        $Mod->startTrans();
        $in_Order_items_Ok = false;
        $inOk = false;
        $in_Log_Ok = false;
        $clear_cart = false;
        $inpayOk = false;
        $couponlogAllOk = false;
        $changeCouAllOk = false;
        $giftCoupon  = true;
        $is_buy_log  = true;
        $in_bonus_log_Ok  = true;
        $in_bonus_use_Ok  = true;
        $Award  = true;
        $bill_pay_statu['status']  = true;
        //分单
        $order_num = $this->createNonceStr();


        //print_r($carts);exit;
        $total_pay = 0;
        $is_k = 0;
        foreach ($carts as $k => $local) {



            if ($local['checked_num'] > 0) {

                $lastcoupon = array();
                //正确的优惠卷数组


                foreach ($coupon_array as $vv => $ca){
                     if($vv == $local['local_id']){
                         $lastcoupon =  $this->choice($ca,$local['local_total']);
                     }
                }


                //更新该用户优惠卷数据

                if ($local['shipping'] == 2) {
                    //自提
                    $orderGroup[$k]['pickedup_bn'] = $local['mobile'];//自提验证【电话号码】
                    if (empty($local['mobile'])) {
                        $this->ajaxReturn(array('status' => 1, 'msg' => '自提电话不能为空'));
                    }
                    $orderGroup[$k]['shipping'] = '门店自提';//配送方式名
                    $orderGroup[$k]['isStore_delivery'] = 3; //自提
                   // $orderGroup[$k]['shipping_id'] = $local['shipping'];//配送方式 ID
                    $orderGroup[$k]['confirm'] = "Y";//(送货上门 'N', 门店自提 'Y')
                    $orderGroup[$k]['is_zt'] = 1;//是否自提
                    $orderGroup[$k]['zT_addr'] = $local['zT_addr'];//订单自提地址

                } elseif ($local['shipping'] == 1) {

                    if($local['inner_type']==1){
                        $orderGroup[$k]['shipping'] = '店铺速配';//门店配送
                        $orderGroup[$k]['isStore_delivery'] = 1;//门店配送
                    }elseif($local['inner_type']==2){
                        $orderGroup[$k]['shipping'] = '快递';//快递配送
                        $orderGroup[$k]['isStore_delivery'] = 2;//快递配送
                    }else{
                        //全国送
                        $orderGroup[$k]['shipping'] = '快递';//快递配送
                        $orderGroup[$k]['isStore_delivery'] = 2;//快递配送
                    }

                 //   $orderGroup[$k]['shipping_id'] = $local['shipping'];//配送方式 ID
                    $orderGroup[$k]['confirm'] = "N";//(送货上门 'N', 门店自提 'Y')
                }


                if(!empty($local['supplier_id'])){
                    $orderGroup[$k]['supplier_id'] = $local['supplier_id'];//供应商ID
                }


                $orderGroup[$k]['shipping_id'] = $local['send_type'];
                $orderGroup[$k]['ship_time'] = $local['expected_time'];//配送时间

                //$orderGroup[$k]['pickedup_time'] = $local['expected_time'];//自提时间
                // echo $local['expected_time'].'---';


                $orderGroup[$k]['order_id'] = $this->createOrderId();//订单ID
                $orderGroup[$k]['message'] = '0';//订单提醒 默认是0


                //使用优惠卷，最终价格
                if(!empty($lastcoupon)&&isset($lastcoupon)){
                    $orderGroup[$k]['total_amount'] = $lastcoupon['money'];
                    $orderGroup[$k]['pmt_coupon'] = $lastcoupon['discmoney'];
                    $orderGroup[$k]['coupon_id'] = $lastcoupon['sj'];

                    //print_r(unserialize($orderGroup[$k]['coupon_id']));

                }else{
                    $orderGroup[$k]['total_amount'] = $local['local_total'];//门店 总价格，包含运费[促销方式等]最终支付的价格
                }


                //$orderGroup[$k]['final_amount'] = $local['local_total'];//门店货币结算金额 【结合促销方式(优惠卷等)待更改】 【再确认一下】
                $orderGroup[$k]['cost_item'] = $local['lp_fee'];//订单商品总价格

                /****冉 3-9 入库物流费用判断是否是免邮费，免邮费运费为 0 入库******/
                $isfound_free_cost = false;
                if(!empty($local['order_pro'])){
                    foreach ($local['order_pro'] as $op =>$opValue){
                        if($opValue['type_result'] == '1'){
                            $orderGroup[$k]['cost_freight'] = 0;//订单促销免运费 物流费用 设置为0
                            $isfound_free_cost = true;
                            break;
                        }
                    }
                }
                if(!$isfound_free_cost){
                    $orderGroup[$k]['cost_freight'] = $local['ship_fee'];//物流费用
                }


                /************************************************************/

                $orderGroup[$k]['pmt_order'] = $local['disOrderMoney'];//订单促销
                $orderGroup[$k]['order_msg'] = '未支付';//下单未支付



                $is_order_pro['disc_order_money'] =$local['disOrderMoney'];
                $is_order_pro['disc_order_desc'] =$local['order_pro'];
                $is_order_pro['gift_coupon'] =$local['gift_coupon'];
                if(!empty($is_order_pro['disc_order_desc'] )){
                    $orderGroup[$k]['order_promotions'] = serialize($is_order_pro);
                }




                //`pmt_goods` decimal(20,3) DEFAULT NULL COMMENT '商品促销优惠',
                //`pmt_order` decimal(20,3) DEFAULT NULL COMMENT '订单促销优惠',
                //`discount` decimal(20,3) NOT NULL DEFAULT '0.000' COMMENT '订单减免',


                $orderGroup[$k]['createtime'] = time();//订单创建时间
                $orderGroup[$k]['last_modified'] = time();//初始跟下单时间一致
                //var_dump($k) ;exit;
                $orderGroup[$k]['payment'] = $data['order'][$is_k]['pay_method'];//支付方式





                $orderGroup[$k]['paymethod_id'] = $data['order'][$is_k]['pay_method_id'];//来源


                $orderGroup[$k]['member_id'] = session('userInfo')['member_id'];//会员ID
                $orderGroup[$k]['ship_area'] = $userAddr['area'];//收货地址
                $orderGroup[$k]['ship_name'] = $userAddr['name'];//收货人
                $orderGroup[$k]['ship_addr'] = $userAddr['addr'];//收货详细
                $orderGroup[$k]['ship_mobile'] = $userAddr['mobile'];//收货人手机



                $orderGroup[$k]['order_refer'] = '微信';//订单来源【待修改】
                $orderGroup[$k]['source'] = 'weixin';//来源

                $orderGroup[$k]['status'] = 'active';//订单状态，初始下单 active
                $orderGroup[$k]['weight'] = $local['total_weight'];//订单总重量

                $orderGroup[$k]['ip'] = $_SERVER["REMOTE_ADDR"];//IP地址

                /******************5-18 奖金支付**********************/
                if ($local['local_id'] == $data['order'][$is_k]['local_id']) {
                    $orderGroup[$k]['memo'] = $data['order'][$is_k]['msg'];//订单附言
                    $orderGroup[$k]['bonus_pay'] = $data['order'][$is_k]['bonus'];//奖金支付金额
                }
                if(empty($data['order'][$is_k]['bonus'])){
                    $orderGroup[$k]['bonus_pay'] = 0;
                }
                if($local['bonus_proportion']>0){
                        //佣金比例奖金
                    $orderGroup[$k]['bonus_proportion'] = $local['bonus_proportion'];//奖金支付金额
                }
                /*******************5-18** 判断支付方式*******************/

                $total_pay +=  ($orderGroup[$k]['total_amount'] - $orderGroup[$k]['bonus_pay']);

                if($orderGroup[$k]['total_amount'] - $orderGroup[$k]['bonus_pay'] == 0){
                    $orderGroup[$k]['paymethod_id'] = 5;//支付方式
                    $pay_cont = new  PayController();
                    $order_data = array();
                    $order_data = [
                        'order_id' => $orderGroup[$k]['order_id'],
                        'local_id' => $local['local_id'],
                        'total_amount' => $orderGroup[$k]['total_amount'],
                        'cost_freight' => $orderGroup[$k]['cost_freight'],
                        'createtime' => $orderGroup[$k]['createtime'],
                        'paymethod_id' => 5,
                        'cost_item' => $local['lp_fee'],
                        'time' => time(),
                        'member_id' => $this->member_id,
                        'ship_mobile' => $orderGroup[$k]['ship_mobile'],
                        'order_promotions' => $orderGroup[$k]['order_promotions'],
                        'bonus_pay' => $orderGroup[$k]['bonus_pay'],

                    ];
                   $bill_pay_statu =  $pay_cont->saveTable($order_data,'','',5);
                }


                if($data['order'][$is_k]['bonus']>0){

                    //奖金 使用log
                    $in_bonus_log_Ok = M('b2c_bonus_log')->add([
                        'local_id'=>$local['local_id'],
                        'member_id'=>$this->member_id,
                        'type'=>'1',
                        'change'=>'5',
                        'change_num'=>-$data['order'][$is_k]['bonus'],
                        'param' => $orderGroup[$k]['order_id'].',-'.$data['order'][$is_k]['bonus'],
                        'time'=>time(),
                        'msg'=>'自己使用奖金抵扣订单',
                    ]);
                    if($in_bonus_log_Ok ===false){
                        break;
                    }else{
                        //减去 使用奖金
                        $in_bonus_use_Ok = M('distribution_member')->where(['local_id'=>$local['local_id'],'member_id'=>$this->member_id])->setDec(
                            'current_bonus',$data['order'][$is_k]['bonus']);
                        if($in_bonus_use_Ok ===false){ break; }

                    }

                    if( $total_pay > 0){
                        $orderGroup[$k]['payment'] = '奖金支付+'.$orderGroup[$k]['payment'] ;
                    }elseif($total_pay == 0){
                        $orderGroup[$k]['payment'] = '奖金支付';
                        $orderGroup[$k]['pay_status'] = '1';
                        $orderGroup[$k]['order_msg'] = '已支付';
                    }
                }

                /****************************************************************/

                $orderGroup[$k]['local_id'] = $local['local_id'];//门店ID
                $orderGroup[$k]['local_name'] = $local['local_name'];//门店名
                $orderGroup[$k]['relation_local_id'] = $local['default_local_id'];//店铺会员购买全国送商品ID

                $orderGroup[$k]['order_num'] = $order_num;//支付num

                $order_total_num = 0;


                //商品名称

                $str_goods_name = '';
                foreach ($local['products'] as $lk => $vall) {

                    if (isset($vall['group_products'])) {


                        //组合套餐
                        foreach ($vall['group_products'] as $gk => $val) {
                            if ($val['ischeck'] == 1 && ($vall['active'] == 1 || $vall['active_ident'] == 1)) {
                                $orderGroupItem[$gk]['order_id'] = $orderGroup[$k]['order_id']; //订单ID
                                $order_total_num += $val['num'];
                                $orderGroupItem[$gk]['product_id'] = $val['product_id'];
                                $orderGroupItem[$gk]['goods_id'] = $val['goods_id'];
                                $orderGroupItem[$gk]['bn'] = $val['bn'];
                                $orderGroupItem[$gk]['name'] = $val['product_name'];
                                $str_goods_name = $str_goods_name.$val['product_name'].',';
                                //订单商品是否身份验证
                                if($val['is_identity_card'] == 'true'){
                                    if($val['is_identity_card_photo'] == 'true'){
                                        $orderGroupItem[$gk]['identity_card_status'] = '2';
                                    }elseif($val['is_identity_card_photo'] == 'false'){
                                        $orderGroupItem[$gk]['identity_card_status'] = '1';
                                    }
                                }


                                //全国送 抽佣计算

                                $order_qgs_fee = $this->yc_fee($val['product_id'], $vall['local_id'], $val['cart_num'], 0,1,$vall['group_id'],1);
                                $order_yc_fee = $this->yc_fee($val['product_id'], $vall['local_id'], $val['cart_num'], 0,1,$vall['group_id'],0);
                                $orderGroupItem[$gk]['price'] =  number_format(bcmul($order_yc_fee['discout'], $val['price'], 6), 2, '.', '');
                                $orderGroupItem[$gk]['g_price'] = $val['price'];//明细商品的会员价原价//【待修改】
                                $isA = bcmul($order_yc_fee['discout'],$val['price'],6);
                                $isB = bcmul($val['num'],$val['cart_num'],6);
                                $isC =  bcmul($isA,$isB,6);

                                $orderGroupItem[$gk]['amount'] = number_format($isC, 2, '.', '');//明细商品总额//【待修改】
                                $orderGroupItem[$gk]['nums'] = $val['num'] * $val['cart_num'];//明细商品购买数量
                                $orderGroupItem[$gk]['store_pid'] = $val['store_pid'];//门店商品ID


                                $orderGroupItem[$gk]['weight'] = $val['total_weight'];//商品重量
                                $orderGroupItem[$gk]['item_type'] = 'pkg';//捆绑商品、组合促销
                                $orderGroupItem[$gk]['addon'] = $val['spec_info'];//商品属性，存入order_item【待修改】

                                $orderGroupItem[$gk]['yc_fee'] = number_format($order_yc_fee['yc_fee'], 2, '.', '');// 怡臣 获取费用
                                $orderGroupItem[$gk]['yc_rate'] = number_format($order_yc_fee['yc_rate'], 2, '.', '');//怡臣收费率

                                $orderGroupItem[$gk]['qgs_fee'] = number_format($order_qgs_fee['yc_fee'], 2, '.', '');// 全国送 获取费用
                                $orderGroupItem[$gk]['qgs_rate'] = number_format($order_qgs_fee['yc_rate'], 2, '.', '');//全国送收费率

                                $orderGroupItem[$gk]['tag_id'] = $vall['group_id'];//组合商品【待修改】

                                //入库order_items
                                $in_Order_items_Ok = M('b2c_order_items')->add($orderGroupItem[$gk]);
                                /*echo "|";
                                echo  M("b2c_order_items")->getLastSql();exit;*/
                                if($in_Order_items_Ok){
                                    //冻结库存
                                    $addFreez =  M('b2c_store_product')->where(['product_id'=>$val['product_id'],'local_id'=>$vall['local_id']])->setInc('freez',$orderGroupItem[$gk]['nums']);
                                    //清除购物车
                               $clear_cart = M('b2c_carts')->where(['group_id'=>$vall['group_id'],'local_id'=>$vall['local_id'],'member_id'=>session('userInfo')['member_id']])->delete();
                                   /* echo "|";
                                    echo  M("b2c_carts")->getLastSql();*/
                                }

                            }
                        }

                    } else {

                        if ($vall['ischeck'] == 1 && ($vall['active'] == 1 ||$vall['active_ident'] == 1)) {
                            //普通商品
                            $orderItem[$lk]['order_id'] = $orderGroup[$k]['order_id']; //订单ID
                            //ordre_source
                            $orderItem[$lk]['product_id'] = $vall['product_id'];
                            $orderItem[$lk]['goods_id'] = $vall['goods_id'];
                            //type_id
                            $orderItem[$lk]['bn'] = $vall['bn'];
                            $orderItem[$lk]['name'] = $vall['name'];
                            $str_goods_name = $str_goods_name.$vall['name'].',';

                            //cost
                            $orderItem[$lk]['price'] = $vall['final_price'];

                            //订单商品是否身份验证
                            if($vall['is_identity_card'] == 'true'){
                                if($vall['is_identity_card_photo'] == 'true'){
                                    $orderItem[$lk]['identity_card_status'] = '2';
                                }elseif($vall['is_identity_card_photo'] == 'false'){
                                    $orderItem[$lk]['identity_card_status'] = '1';
                                }

                            }


                            //闪购
                            if($vall['type']==2){
                                $orderItem[$lk]['item_type'] = 'sg';
                            }elseif ($vall['type']==0){
                                $orderItem[$lk]['item_type'] = 'product';//明细商品类型 初始product 普通商品
                            }

                            $orderItem[$lk]['g_price'] = $vall['price'];//商品原价
                            $orderItem[$lk]['amount'] =  bcmul($vall['final_price'], $vall['cart_num'], 2); //明细商品总额
                            $orderItem[$lk]['weight'] = $vall['weight'];//商品重量
                            $orderItem[$lk]['nums'] = $vall['cart_num'];//明细商品购买数量
                            $orderItem[$lk]['store_pid'] = $vall['store_pid'];//门店商品ID
                            $orderItem[$lk]['addon'] = $vall['spec_info'];//商品属性，存入order_item【待修改】

                            $order_yc_fee = $this->yc_fee($vall['product_id'], $vall['local_id'], $vall['cart_num'], $vall['final_price'],0,0,0);
                            $order_qgs_fee = $this->yc_fee($vall['product_id'], $vall['local_id'], $vall['cart_num'], $vall['final_price'],0,0,1);

                            $orderItem[$lk]['yc_fee'] = number_format($order_yc_fee['yc_fee'], 2, '.', '');// 怡臣 获取费用
                            $orderItem[$lk]['yc_rate'] = number_format($order_yc_fee['yc_rate'], 2, '.', '');
                            $orderItem[$lk]['qgs_fee'] = number_format($order_qgs_fee['yc_fee'], 2, '.', '');// 怡臣 获取费用
                            $orderItem[$lk]['qgs_rate'] = number_format($order_qgs_fee['yc_rate'], 2, '.', '');
                            $order_total_num += $vall['cart_num'];
                            //入库order_items
                           $in_Order_items_Ok = M('b2c_order_items')->add($orderItem[$lk]);

                            if($in_Order_items_Ok){
                                //冻结库存

                                if($vall['type']==2){
                                    $addFreez =  M('starbuy_flashsales_goods')->where(['id'=>$vall['sg_id']])->setdec('initnum',$orderItem[$lk]['nums']);
                                    //添加用户购买闪购记录
                                    $is_buy_log = M('starbuy_count_member_buy')->add([
                                        'store_pid' => $vall['store_pid'],
                                        'member_id' => session('userInfo')['member_id'],
                                        'count' => $orderItem[$lk]['nums'],
                                        'fg_id' => $vall['sg_id'],
                                    ]);

                                }elseif ($vall['type']==0){
                                    $addFreez =  M('b2c_store_product')->where(['product_id'=>$vall['product_id'],'local_id'=>$vall['local_id']])->setInc('freez',$orderItem[$lk]['nums']);
                                }


                                //清除购物车
                           $clear_cart = M('b2c_carts')->where(['local_id'=>$vall['local_id'],'product_id'=>$vall['product_id'],'member_id'=>session('userInfo')['member_id']])->delete();


                            }

                        }
                    }

                }


                if($orderGroup[$k]['total_amount'] - $orderGroup[$k]['bonus_pay']==0){
                    //下属提成
                    $Award  = shoppingAwardBonus($this->member_id,$local['local_id'], $orderGroup[$k]['order_id'], $orderGroup[$k]['total_amount'],$str_goods_name);
                }



                $orderGroup[$k]['itemnum'] = $order_total_num;//
                //入库操作orders
                $inOk = M('b2c_orders')->add($orderGroup[$k]);

                //订单记录log日志，创建成功
                $log[$k]['rel_id'] = $orderGroup[$k]['order_id'];
                $log[$k]['op_id'] = session('userInfo')['member_id'];

                $log[$k]['op_name'] = session('userInfo')['mobile'];
                $log[$k]['alttime'] = time();
                $log[$k]['bill_type'] = 'order';
                $log[$k]['behavior'] = 'creates';
                $log[$k]['result'] = 'SUCCESS';
                $log[$k]['log_text'] = '订单创建成功！';
                $in_Log_Ok = M('b2c_order_log')->add($log[$k]);



                //优惠卷使用日志

                if(!empty($lastcoupon)&&isset($lastcoupon)){

                    //修改优惠卷已经被该用户 使用
                   $use_coupon =  unserialize($lastcoupon['sj']);
                    foreach ($use_coupon as $cou =>$item){
                        $changeCouOk = M('b2c_discount_coupon_code')->where(['local_id'=>$item['local_id'],'discount_coupon_id'=>$item['id'],'code'=>$item['code'],'member_id'=>session('userInfo')['member_id']])->save(array('status'=>1,'use_time'=>date('Y-m-d H:i:s',time())
                    ));

                        if($changeCouOk !== false){
                            $changeCouAllOk = $changeCouOk;
                        }else{
                            $changeCouAllOk = $changeCouOk;
                            break;
                        }
                    }


                    $logcoupon['log_text'] = serialize($lastcoupon);

                    $logcoupon['order_id'] = $orderGroup[$k]['order_id'];
                    $logcoupon['op_id'] = session('userInfo')['member_id'];
                    $logcoupon['op_name'] = $log[$k]['op_name'];
                    $logcoupon['alttime'] = time();
                    $logcoupon['type'] = '1';

                   $incouponlogOk = M('b2c_promotions_log')->add($logcoupon);

                   // var_dump($incouponlogOk);
                    if($incouponlogOk !== false){
                        $couponlogAllOk = $incouponlogOk;
                    }else{
                        $couponlogAllOk = $incouponlogOk;
                        break;
                    }
                }else{
                    $couponlogAllOk = true;
                }

                 $is_k++;

                /*echo "|";
                echo  M("b2c_order_log")->getLastSql();*/
            }
        }


        //入库order_num 表
        /*****************5-19 奖金支付************************/
        if($total_pay > 0){
            $payData = array();
            $payData['order_num'] =$order_num;
            $payData['cost_money'] =$total_pay;
            $payData['create_time'] =time();
            $payData['pay_id'] =$pay_id;
            $inpayOk = M('b2c_order_num')->add($payData);
        }else{
            $inpayOk = true;
        }
        /***********************************/
        if ($in_Order_items_Ok !== false && $inOk !== false && $in_Log_Ok !== false && $clear_cart !== false && $addFreez !==false && $is_buy_log !==false && $inpayOk !== false &&  $couponlogAllOk !== false && $giftCoupon === true && $in_bonus_log_Ok !==false && $in_bonus_use_Ok !== false && $Award !==false && $bill_pay_statu['status'] !==false){
            // 提交事务
            $Mod->commit();
        }else{
            // 事务回滚
            $Mod->rollback();
            $this->ajaxReturn(array('msg'=>'下单失败','status'=>0));
        }
        /*****************5-19 奖金支付************************/

        if($total_pay > 0){
            $this->ajaxReturn(array('msg'=>'下单成功','status'=>1,'url'=>U('Pay/weixinpay',array('id'=>$order_num))));
        }elseif($total_pay == 0){
            $this->ajaxReturn(array('msg'=>'下单成功','status'=>1,'url'=>U('Pay/paySuccess',array('order_num'=>$order_num))));
        }
        //$this->redirect('Pay/weixinpay', array('id' => $order_num));
    }
    //优惠卷选择判断
    public function choice($coupon_array,$total_money){
        //print_r($coupon_array);
        $resultCoupon = array();
        if(isset($coupon_array['paita'])){
            //有排他的情况下，只取一条
            unset($coupon_array['paita']);
            $arr = [];
            $arr1 = [];
            foreach ($coupon_array as $k=>$v){
                $arr[] = $v['paita'];
                $arr1[] = $v['sort'];
            }
            array_multisort($arr, SORT_DESC,$arr1, SORT_ASC,$coupon_array);
            $resultCoupon[] = current($coupon_array);

            $now_money = $total_money;
            $discmoney = 0;
            if($resultCoupon[0]['type']=='1' && ($total_money-$resultCoupon[0]['money_price'])>=1){
                $now_money = $total_money-$resultCoupon[0]['money_price'];
                $discmoney = $resultCoupon[0]['money_price'];
            }elseif($resultCoupon[0]['type']=='2' && ($total_money>=$resultCoupon[0]['man_price']) && ($total_money-$resultCoupon[0]['youhui_price'])>=1){

                $now_money = $total_money-$resultCoupon[0]['youhui_price'];
                $discmoney = $resultCoupon[0]['youhui_price'];
            }elseif($resultCoupon[0]['type']=='3' && ($total_money-$resultCoupon[0]['goods_price'])>=1){
                $now_money = $total_money-$resultCoupon[0]['goods_price'];
                $discmoney = $resultCoupon[0]['goods_price'];
            }
            $resultCoupon[0] = $resultCoupon;
            $resultCoupon['money'] = $now_money;
            $resultCoupon['discmoney'] = $discmoney;
        }else{
            //没有排他 多选 排序
            $arrno = [];
            foreach ($coupon_array as $k=>$value){
                $arrno[] = $value['sort'];
            }

            array_multisort($arrno, SORT_ASC,$coupon_array);


            $now_money = $total_money;


            $discmoney = 0;
            foreach ($coupon_array as $k =>$item){

                if($item['type']=='1' && ($now_money-$item['money_price'])>=1){
                     $now_money = $now_money-$item['money_price'];
                     $discmoney += $item['money_price'];
                    $resultCoupon['sj'][$k] = $item;
                    $resultCoupon['coupon_id'][$k] = $item['id'];
                    continue;
                }

                if($item['type']=='2' &&  ($now_money-$item['youhui_price'])>=1){

                   $now_money = $now_money-$item['youhui_price'];
                   $discmoney += $item['youhui_price'];
                    $resultCoupon['sj'][$k] = $item;
                    $resultCoupon['coupon_id'][$k] = $item['id'];
                    continue;
                }
                if($item['type']=='3' && ($now_money-$item['goods_price'])>=1){

                    $now_money = $now_money-$item['goods_price'];
                    $discmoney += $item['goods_price'];
                    $resultCoupon['sj'][$k] = $item;
                    $resultCoupon['coupon_id'][$k] = $item['id'];
                    continue;
                }

            }

            $resultCoupon['coupon_id'] = serialize($resultCoupon['coupon_id']);
            $resultCoupon['sj'] = serialize($resultCoupon['sj']);
            $resultCoupon['money'] = $now_money; //选择优惠卷后的店铺总价
            $resultCoupon['discmoney'] = $discmoney;
        }
        //print_r($resultCoupon);exit;
        return $resultCoupon;
    }


    /*
     *生成订单号
     **/
    public function createOrderId()
    {
        $i = rand(0,99999);
        do{
            if(99999==$i){
                $i=0;
            }
            $i++;
            $order_id = date('ymdHi').str_pad($i,5,'0',STR_PAD_LEFT);
           $result = M('b2c_orders')->where(['order_id'=>$order_id])->find();
            if(empty($result)){
                $row= false;
            }else{
                $row= true;
            }

        }while($row);
        return $order_id;
    }
    /**
     * 计算平台服务费
     */
    public function yc_fee($pid,$local,$number,$price,$type,$group_id,$is_qgs){
       /* echo $pid.'/';
        echo $local.'/';
        echo $number.'/';
        echo $price.'/';
        echo $type.'/';
        echo $group_id.'/';*/


      if($type==0){


          if($is_qgs == 1){
              $priceStart = M('b2c_carts c')
                  ->join("left join sdb_b2c_store_product sp on c.product_id = sp.product_id AND c.local_id = sp.local_id")
                  ->join("LEFT JOIN sdb_qgs_cat_commission as cc ON cc.cat_id = sp.scate_id AND cc.local_id = sp.local_id")
                  ->where(['c.local_id'=>$local,'c.product_id'=>$pid])
                  ->field("cc.num,cc.local_id,cc.cat_id,sp.price,sp.marketprice,sp.product_id,sp.goods_id")
                  ->find();


          }else{
              $priceStart = M('b2c_carts c')
                  ->join("left join sdb_b2c_goods  g on g.goods_id = c.goods_id")
                  ->join("left join sdb_b2c_store_product sp on c.goods_id = sp.goods_id AND c.local_id = sp.local_id")
                  ->join("LEFT JOIN sdb_b2c_store_cat_commission as cc ON cc.cat_id = g.cat_id AND cc.local_id = sp.local_id")
                  ->where(['c.local_id'=>$local,'c.product_id'=>$pid])
                  ->field("cc.num,cc.local_id,cc.cat_id,sp.price,sp.marketprice,sp.product_id,sp.goods_id")
                  ->find();


          }

        // 12-29佣金如果后台没有设置保存，默认为2
          if(empty($priceStart['num'])){
              $priceStart['num'] = 2;
          }


          $slv =  bcdiv($priceStart['num'], 100, 6) ;
          $np = bcmul($number, $price, 6);
          $yc_fee = bcmul($slv, $np, 6);


          /*echo $number.'|'.$price.'|';
          echo $np.'|';
          echo $yc_fee;
          exit;*/

          $yc_fee = number_format($yc_fee, 2, '.', '');


          $price_result = array(
              'yc_fee'=>$yc_fee,
              'yc_rate'=>$priceStart['num'],
          );


      }elseif ($type==1){
           //平台费率


          if($is_qgs == 1){
              $priceStart = M('b2c_carts c')
                  ->join("left join sdb_b2c_store_product sp on c.product_id = sp.product_id AND c.local_id = sp.local_id")
                  ->join("LEFT JOIN sdb_qgs_cat_commission as cc ON cc.cat_id = sp.scate_id AND cc.local_id = sp.local_id")
                  ->where(['c.local_id'=>$local,'c.product_id'=>$pid])
                  ->field("cc.num,cc.local_id,cc.cat_id,sp.price,sp.marketprice,sp.product_id,sp.goods_id")
                  ->find();

              $priceStart=M()->query("SELECT g.local_id,gi.product_id,g.total_price,gi.num,sp.price,cc.num as lv from sdb_b2c_store_promotion_group_item gi
      LEFT JOIN sdb_b2c_store_promotion_group g on g.id=gi.group_id
      LEFT JOIN sdb_b2c_store_product sp on sp.store_pid = gi.sp_id
      LEFT JOIN sdb_b2c_store_cat_commission cc  on cc.cat_id = sp.scate_id AND cc.local_id = g.local_id
      where gi.group_id =$group_id");

          }else{
              $priceStart=M()->query("SELECT g.local_id,gi.product_id,g.total_price,gi.num,sp.price,cc.num as lv from sdb_b2c_store_promotion_group_item gi
      LEFT JOIN sdb_b2c_store_promotion_group g on g.id=gi.group_id
      LEFT JOIN sdb_b2c_store_product sp on sp.store_pid = gi.sp_id
      LEFT JOIN sdb_b2c_goods go on go.goods_id = sp.goods_id
      LEFT JOIN sdb_b2c_store_cat_commission cc  on cc.cat_id = go.cat_id AND cc.local_id = g.local_id
      where gi.group_id =$group_id");

          }





          $total =0;
          $final_price =0;

           foreach ($priceStart as $k=>$value){
               //$total += $value['price']*$value['num'];


               $isNewA = bcmul($value['price'], $value['num'], 6);
               $total =  bcadd($isNewA, $total, 6);

               $final_price = $value['total_price'];
           }

           $discout =  bcdiv($final_price, $total, 6);


           foreach ($priceStart as $kk=>$val){

               // 12-29佣金如果后台没有设置保存，默认为2
               if(empty($val['lv'])){
                   $val['lv'] = 2;
               }

               if($pid==$val['product_id']){

                   $isNewD = bcmul($val['price'], $discout, 6);
                   $isNewB = bcdiv($val['lv'], 100, 6);
                   $isNewC = bcmul($isNewD, $isNewB, 6);
                   $isNewE = bcmul($val['num'], $number, 6);
                   $price_result['yc_fee'] = bcmul($isNewC, $isNewE, 6);
                   $price_result['discout'] = $discout;
                   $price_result['yc_rate'] = $val['lv'];
               }

           }
      }
        return $price_result;
    }


    /**
     * 店铺抽佣服务费
     */


    public function createNonceStr($pack = 'wx') {
        $code = $pack;
        $code .= time();
        $chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $code .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        return $code;
    }

    public function deep_in_array($value, $array) {
        foreach($array as $item) {
            if(!is_array($item)) {
                if ($item == $value) {
                    return true;
                } else {
                    continue;
                }
            }
            if(in_array($value, $item)) {
                return true;
            } else if($this->deep_in_array($value, $item)) {
                return true;
            }
        }
        return false;
    }

}